<?php

namespace app\api\controller;

use app\api\model\AboutUs;
use app\api\model\CircleLikes;
use app\api\model\Circles;
use app\api\model\Designs;
use app\api\model\Orders;
use app\api\model\OrderVip;
use app\api\model\Recharges;
use app\api\model\Users;
use app\api\model\Users as UserModel;
use app\api\model\Wechat;
use app\common\controller\Api;
use app\common\library\Token;
use think\Cache;
use Yansongda\Pay\Exceptions\GatewayException;
use app\api\model\UserPayment as UserPaymentModel;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['auth', 'code', 'about', 'service'];
    protected $noNeedRight = '*';

    /**
     * 授权
     */
    public function auth()
    {
        $code = $this->request->post('code');
        $merchant_id = $this->request->post('merchant_id');
        if (empty($code)) {
            $this->error('code不能为空');
        }
        //小程序登录
        $token = md5(sha1(time()) . $code);
        $res = (new Wechat($code))->getAuth($token);
        if (isset($res['errcode']) && $res['errcode'] !== 0) {
            $this->error($res['errmsg'], [], $res['errcode']);
        }
        //是否首次授权
        $user = UserModel::where('openid', $res['openid'])->find();
        if (!$user) {
            $user = UserModel::create(['openid' => $res['openid']]);
            if ($merchant_id) {
                //推广的合作商
                $user->merchant_id = $merchant_id;
                $user->save();
            }
        }
        if ($user->is_freeze) {
            $this->error('您已被冻结使用，请联系客服', [], 10001);
        }
        //刷新token
        $result = Token::set($token, $user->id, 2592000);
        if (!$result) {
            $this->error('授权失败');
        }
        $this->success('授权成功', ['token' => $token]);
    }

    /**
     * 更新头像昵称
     */
    public function update()
    {
        $data = $this->request->post();
        if (!$data) {
            $this->error('请求参数不能为空');
        }
        $user = UserModel::find($this->auth->getUserId());
        if (!$user) {
            $this->error('用户不存在');
        }

        $user->head = $data['head'] ?? $user->head;
        $user->nickname = $data['nickname'] ?? $user->nickname;
        $user->phone = $data['phone'] ?? $user->phone;
        $user->sex = $data['sex'] ?? $user->sex;
        $result = $user->save();
        $result ? $this->success('更新成功') : $this->error('更新失败');
    }

    /**
     * 获取小程序码
     */
    public function code(Wechat $wechat)
    {
        $data = $this->request->post();
        $dir = ROOT_PATH . 'public/uploads/wechat/';
        $filePath = $dir . md5($data['scene'] ?? '') . '.png';
        if (!file_exists($filePath)) {
            //获取小程序码
            $res = $wechat->getORCode($data);
            if (isset($res['errcode'])) {
                $this->error($res['errmsg'], [], $res['errcode']);
            }
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
            //将二进制小程序码转换为图片保存
//            $file = fopen($filePath, 'W');
//            $fw = fwrite($file, $res);
//            if ($fw === FALSE ) {
//                $this->error('获取小程序码异常');
//            }
//            fclose($file);
            file_put_contents($filePath, $res);
        }
        $image = str_replace(ROOT_PATH . 'public', $this->request->domain(), $filePath);
        $this->success('请求成功', ['image' => $image]);
    }

    /**
     * 微信小程序解密数据
     */
    public function decryptData()
    {
        $encryptedData = $this->request->post('encryptedData');
        $iv = $this->request->post('iv');
        $token = $this->request->header('token');
        $session_key = Cache::get($token);
        if (strlen($session_key) != 24) {
            $this->error('session_key无效', [], -41001);
        }
        if (strlen($iv) != 24) {
            $this->error('iv无效', [], -41002);
        }
        $aesKey = base64_decode($session_key);
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $data = json_decode($result, true);
        if (!$data) {
            $this->error('没有数据', [], -41003);
        }
        if( $data['watermark']['appid'] != config('wechat.app_id') ) {
            $this->error('appid无效', [], -41003);
        }
        $this->success('请求成功', $data);
    }

    /**
     * 我的收藏
     */
    public function like()
    {
        $page = $this->request->get('page');
        $length = $this->request->get('length');
        $circle_id = CircleLikes::getUserLike($this->auth->getUserId());
        if (!$circle_id) {
            $this->error('没有数据', [], 2);
        }
        $circles = Circles::getUserCircles($circle_id, $length);
        if (!$circles->items()) {
            $this->error('没有数据', [], 2);
        }
        $circles = $circles->items();
        array_walk($circles, function (&$val) {
            return $val->like = 1;
        });
        $this->success('请求成功', ['circles' => $circles]);
    }

    /**
     * 获取用户信息
     */
    public function info()
    {
        $user = Users::with('userVip')->withCount('userCoupons')->find($this->auth->getUserId());
        if (!$user) {
            $this->error('没有数据');
        }
        $user->design = Designs::where('phone', $user->phone)->find();
        $this->success('请求成功', ['user' => $user]);
    }

    /**
     * 关于拾玖
     */
    public function about()
    {
        $content = AboutUs::value('content');
        $content ? $this->success('请求成功', ['content' => $content]) : $this->error('没有数据', [], 2);
    }

    /**
     * 联系客服
     */
    public function service()
    {
        $content = getSetting(config('setting.services'));
        $content ? $this->success('请求成功', ['content' => $content]) : $this->error('没有数据', [], 2);

    }

    /**
     * 买单记录
     */
    public function paymentLog()
    {
        $log = UserPaymentModel::getByUserId($this->auth->getUserId());
        $log ? $this->success('请求成功', compact('log')) : $this->error('暂无记录', '', 1);
    }


}
